package com.controller;

import com.model.UserModel;
import com.services.IUserServices;
import com.services.impl.UserServicesImpl;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Program: exam
 * @ClassName: FindAllUserServletController
 * @Description: 查找所有User
 * @Author: li
 * @Create: 2019-07-23 10:05
 */
@WebServlet("/FindAllUserServlet")
public class FindAllUserServletController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        IUserServices services = new UserServicesImpl();
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=UTF-8");

        // 获取搜索参数
        String username = request.getParameter("username");
        String email = request.getParameter("email");
        String tel = request.getParameter("tel");

        // 查询用户列表
        List<UserModel> userModels = services.queryAllUser();
        
        // 添加日志打印
        System.out.println("查询到的用户数量: " + userModels.size());
        System.out.println("用户数据: " + userModels);
        
        // 处理搜索过滤
        if (username != null && !username.isEmpty()) {
            userModels = userModels.stream()
                    .filter(user -> user.getUsername().contains(username))
                    .collect(Collectors.toList());
        }
        if (email != null && !email.isEmpty()) {
            userModels = userModels.stream()
                    .filter(user -> user.getEmail().contains(email))
                    .collect(Collectors.toList());
        }
        if (tel != null && !tel.isEmpty()) {
            userModels = userModels.stream()
                    .filter(user -> user.getTel().contains(tel))
                    .collect(Collectors.toList());
        }
        
        // 构建返回数据
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("msg", "success");
        Map<String, Object> data = new HashMap<>();
        data.put("records", userModels);
        data.put("total", userModels.size());
        result.put("data", data);

        // 打印返回的JSON数据
        JSONObject jsonObject = JSONObject.fromObject(result);
        System.out.println("返回的JSON数据: " + jsonObject.toString());
        
        response.getWriter().write(jsonObject.toString());
    }
}
